<template>
    <div class="time-price-management">
        <!-- 头部标题和操作按钮 -->
        <div class="header">
            <div class="action-buttons">
                <el-button type="primary" @click="handleAddDate">
                    <i class="el-icon-plus"></i> 新增日期
                </el-button>
            </div>
        </div>
        <!-- 数据表格 -->
        <el-card class="table-card" v-for="(item, index) in timePickerOptions" :key="item.id">
            <el-table :data="item.gridElectricityPriceList" border stripe highlight-current-row
                empty-text="暂无时段数据，请点击新增时段添加">
                <!-- 序号 -->
                <el-table-column type="index" label="序号" width="60" align="center" />
                <!-- 时段名称 -->
                <el-table-column label="时段名称">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.timeSlot" placeholder="请输入时段名称" size="small" />
                    </template>
                </el-table-column>

                <!-- 开始时间 -->
                <el-table-column label="开始时间">
                    <template slot="header" slot-scope="scope">
                        <el-date-picker v-model="item.startDate" type="date" placeholder="选择开始日期" format="MM-dd"
                            value-format="MM-dd">
                        </el-date-picker>
                    </template>
                    <template slot-scope="scope">
                        <el-tooltip :content="getStartTimeTooltip(index, scope.$index)" placement="top">
                            <el-input :value="scope.row.startTime" disabled size="small" style="width: 100%" />
                        </el-tooltip>
                    </template>
                </el-table-column>

                <!-- 结束时间 -->
                <el-table-column label="结束时间">
                    <template slot="header" slot-scope="scope">
                        <el-date-picker v-model="item.endDate" type="date" placeholder="选择结束日期" format="MM-dd"
                            value-format="MM-dd">
                        </el-date-picker>
                    </template>
                    <template slot-scope="scope">
                        <template v-if="scope.$index === item.gridElectricityPriceList.length - 1">
                            <el-tooltip content="最后时段结束时间固定为24:00" placement="top">
                                <el-input value="24:00" disabled size="small" style="width: 100%" />
                            </el-tooltip>
                        </template>
                        <template v-else>
                            <el-time-select v-model="scope.row.endTime" placeholder="请选择结束时间" size="small"
                                style="width: 100%" @change="handleEndTimeChange(index, scope.$index)" />
                        </template>
                    </template>
                </el-table-column>

                <!-- 价格 -->
                <el-table-column label="价格(元)">
                    <template slot-scope="scope">
                        <el-input-number v-model="scope.row.price" :min="0" :max="10000" :step="10" :precision="2"
                            controls-position="right" size="small" style="width: 100%" />
                    </template>
                </el-table-column>


                <!-- 操作 -->
                <el-table-column label="操作" width="240" fixed="right" align="center">
                    <template slot="header" slot-scope="scope">
                        <el-button size="mini" type="primary" icon="el-icon-plus"
                            @click="handleAddRow(index)">添加时段</el-button>
                        <el-button size="mini" type="danger" icon="el-icon-delete" v-if="index != 0"
                            @click="handleDeleteDate(index)">删除日期</el-button>
                    </template>
                    <template slot-scope="scope">
                        <el-button size="mini" type="danger" icon="el-icon-delete"
                            @click="handleDeleteRow(index, scope.$index)" :disabled="isLastRow(index, scope.$index)">
                            删除时段
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
    </div>
</template>

<script>
export default {
    name: 'TimePriceTable',
    data() {
        return {
            // 表格数据
            tableData: [
                {
                    id: 1,
                    timeSlot: '凌晨',
                    startTime: '00:00',
                    endTime: '06:00',
                    price: 50,
                    discount: 0.6,
                    status: 'active',
                    remark: '凌晨时段'
                },
                {
                    id: 2,
                    timeSlot: '夜间',
                    startTime: '18:00',
                    endTime: '24:00',
                    price: 120,
                    discount: 0.7,
                    status: 'active',
                    remark: '夜间时段'
                }
            ],
            // 时间选择器配置
            timePickerOptions: [
                {
                    startDate: '01-01',
                    endDate: '12-31',
                    gridElectricityPriceList: [
                        {
                            id: 1,
                            sortNo: 1,
                            timeSlot: '凌晨',
                            startTime: '00:00',
                            endTime: '06:00',
                            price: 50,
                        },
                        {
                            id: 2,
                            sortNo: 2,
                            timeSlot: '夜间',
                            startTime: '18:00',
                            endTime: '24:00',
                            price: 120,
                        }
                    ],
                }
            ],
            timePickerOptionsNum: [],
            // 下一个ID
            nextId: 4
        }
    },
    computed: {
        // 格式化数据用于显示
        formattedData() {
            return JSON.stringify(this.tableData, null, 2)
        }
    },
    methods: {
        // 新增行 - 插入到倒数第二位
        handleAddRow(index) {
            if (this.timePickerOptions[index].startDate && this.timePickerOptions[index].endDate) {
                let timeTableRow = this.timePickerOptions[index].gridElectricityPriceList;
                if (timeTableRow.length === 0) {
                    // 如果没有数据，添加第一条
                    timeTableRow.push({
                        id: this.nextId++,
                        timeSlot: '默认时段',
                        startTime: '00:00',
                        endTime: '24:00',
                        price: 50,
                        discount: 1,
                        status: 'active',
                        remark: ''
                    })
                    return
                }

                // 计算插入位置（倒数第二位）
                const insertIndex = timeTableRow.length - 1
                const prevRow = timeTableRow[insertIndex - 1] // 新时段的前一个时段

                // 创建新时段 - 结束时间默认为空
                const newRow = {
                    id: this.nextId++,
                    sortNo: 2,
                    timeSlot: '新时段',
                    startTime: prevRow ? prevRow.endTime : '00:00',
                    endTime: '', // 新增时段结束时间默认为空
                    price: 50,
                }

                // 插入到倒数第二位
                timeTableRow.splice(insertIndex, 0, newRow)

                this.updateAllSortNo(timeTableRow)
                // console.log(this.timePickerOptions);
            } else {
                this.$message.warning('请设置日期')
            }
        },
        updateAllSortNo(timeData) {
            timeData.forEach((row, index) => {
                row.sortNo = index + 1; // 索引+1 = 序号（1、2、3...）
            });
        },
        handleAddDate() {
            let timedata = {
                startDate: '01-01',
                endDate: '12-31',
                gridElectricityPriceList: [
                    {
                        id: 1,
                        sortNo: 1,
                        timeSlot: '凌晨',
                        startTime: '00:00',
                        endTime: '06:00',
                        price: 50,
                    },
                    {
                        id: 2,
                        sortNo: 2,
                        timeSlot: '夜间',
                        startTime: '18:00',
                        endTime: '24:00',
                        price: 120,
                    }
                ],
            }
            this.timePickerOptions.push(timedata);
            this.updateTimeContinuity(this.timePickerOptions[this.timePickerOptions.length - 1])
        },
        // 处理结束时间变化
        handleEndTimeChange(index, rowIndex) {
            let timeTableRow = this.timePickerOptions[index].gridElectricityPriceList;
            const currentRow = timeTableRow[rowIndex]

            // 如果是倒数第二行（新增的时段），更新最后时段的开始时间
            if (rowIndex === timeTableRow.length - 2 && currentRow.endTime) {
                const lastRow = timeTableRow[timeTableRow.length - 1]
                lastRow.startTime = currentRow.endTime
            }

            // 更新时间连续性
            this.updateTimeContinuity(index)
        },
        // 删除外层日期表格
        handleDeleteDate(index) {
            this.timePickerOptions.splice(index, 1)
            this.updateTimeContinuity(index)
        },
        // 删除行
        handleDeleteRow(index, rowIndex) {
            let timeTableRow = this.timePickerOptions[index].gridElectricityPriceList;
            // 不能删除最后一行
            if (this.isLastRow(index, rowIndex)) {
                this.$message.warning('不能删除最后一个时段')
                return
            }

            this.$confirm('确定要删除这个时段吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                timeTableRow.splice(rowIndex, 1)

                // 如果删除的是倒数第二行，需要更新最后时段的开始时间
                if (rowIndex === timeTableRow.length - 1) {
                    const newSecondLastRow = timeTableRow[timeTableRow.length - 2]
                    if (newSecondLastRow) {
                        const lastRow = timeTableRow[timeTableRow.length - 1]
                        lastRow.startTime = newSecondLastRow.endTime
                    }
                }

                // 更新时间连续性
                this.updateTimeContinuity(index)

                this.$message.success('删除成功')
            }).catch(() => {
                // 用户取消删除
            })
        },

        // 检查是否为最后一行
        isLastRow(index, rowIndex) {
            let timeTableRow = this.timePickerOptions[index].gridElectricityPriceList;
            return rowIndex === timeTableRow.length - 1
        },

        // 更新时间连续性
        updateTimeContinuity(index) {
            // 确保所有时段时间连续
            let timeTableRow = this.timePickerOptions[index].gridElectricityPriceList;
            for (let i = 0; i < timeTableRow.length; i++) {
                const row = timeTableRow[i]

                // 第一行开始时间必须是00:00
                if (i === 0) {
                    row.startTime = '00:00'
                }

                // 最后一行结束时间必须是24:00，开始时间跟随上一时段
                if (i === timeTableRow.length - 1) {
                    row.endTime = '24:00'
                    // 开始时间自动跟随上一时段
                    if (i > 0) {
                        const prevRow = timeTableRow[i - 1]
                        if (prevRow.endTime) {
                            row.startTime = prevRow.endTime
                        }
                    }
                }

                // 中间行的开始时间 = 上一行的结束时间
                if (i > 0 && i < timeTableRow.length - 1) {
                    const prevRow = timeTableRow[i - 1]
                    if (prevRow.endTime) {
                        row.startTime = prevRow.endTime
                    }
                }
            }

            let timeList = timeTableRow.map((item, index) => ({
                timeslotStart: (item.startTime).toString(),
                timeslotEnd: (item.endTime).toString(),
                sortNo: item.sortNo,
                amount: item.price.toString()
            }));
            let gridElectricityList = this.timePickerOptions.map((item, index) => ({
                dateslotStart: item.startDate,
                dateslotEnd: item.endDate,
                sortNo: index + 1,
                timeList: timeList
            }));
            this.$emit('getGridElectricityPriceList', gridElectricityList)
        },

        // 获取开始时间提示信息
        getStartTimeTooltip(index, rowIndex) {
            let timeTableRow = this.timePickerOptions[index].gridElectricityPriceList;
            if (rowIndex === 0) {
                return '第一时段开始时间固定为00:00'
            } else if (rowIndex === timeTableRow.length - 1) {
                const prevRow = timeTableRow[rowIndex - 1]
                return `开始时间自动跟随上一时段(${prevRow.endTime})，不可修改`
            } else {
                const prevRow = timeTableRow[rowIndex - 1]
                return `开始时间继承自上一时段(${prevRow.endTime})，不可修改`
            }
        },

        // 计算折扣后价格
        calculateDiscountedPrice(row) {
            return row.price * row.discount
        },

        // 计算平均价格
        // calculateAveragePrice() {
        //     if (this.tableData.length === 0) return 0
        //     const total = this.tableData.reduce((sum, row) => sum + this.calculateDiscountedPrice(row), 0)
        //     return total / this.tableData.length
        // },

        // 复制数据到剪贴板
        copyData() {
            const textArea = document.createElement('textarea')
            textArea.value = this.formattedData
            document.body.appendChild(textArea)
            textArea.select()
            document.execCommand('copy')
            document.body.removeChild(textArea)
            this.$message.success('数据已复制到剪贴板')
        }
    },
    mounted() {
        // 初始化时确保时间连续性
        this.updateTimeContinuity(0)
    },
    watch: {
        // 监听数据变化，实时更新时间连续性
        tableData: {
            handler() {
                this.updateTimeContinuity(0)
            },
            deep: true
        }
    }
}
</script>

<style scoped>
.time-price-management {
    padding: 20px;
}

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 0 10px;
}

.header h2 {
    margin: 0;
    color: #303133;
}

.action-buttons {
    display: flex;
    gap: 10px;
}

/* .table-card {
    margin-bottom: 20px;
}

.stats-card {
    margin-top: 20px;
} */

.data-preview-card {
    margin-top: 20px;
}

.preview-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.data-preview {
    background: #f5f7fa;
    padding: 15px;
    border-radius: 4px;
    overflow-x: auto;
    font-size: 12px;
    line-height: 1.4;
    margin: 0;
    max-height: 300px;
    overflow-y: auto;
}

.stats-content {
    display: flex;
    justify-content: space-around;
    align-items: center;
    flex-wrap: wrap;
}

.stat-item {
    text-align: center;
    padding: 10px 20px;
}

.stat-label {
    font-size: 14px;
    color: #606266;
}

.stat-value {
    font-size: 18px;
    font-weight: bold;
    color: #409EFF;
}

.el-table {
    margin-top: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .header {
        flex-direction: column;
        gap: 15px;
        align-items: flex-start;
    }

    .action-buttons {
        width: 100%;
        justify-content: flex-start;
    }

    .stats-content {
        flex-direction: column;
        align-items: flex-start;
    }

    .stat-item {
        padding: 5px 0;
    }
}
</style>